package myzzyl.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import myzzyl.constants.ErrorConstants;
import myzzyl.domain.pojo.Device;
import myzzyl.domain.pojo.DeviceData;
import myzzyl.exception.BusinessException;
import myzzyl.job.vo.IotMsgNotifyData;
import myzzyl.job.vo.IotMsgService;
import myzzyl.service.DeviceDataService;
import myzzyl.mapper.DeviceDataMapper;
import myzzyl.service.DeviceService;
import org.apache.logging.log4j.util.LoaderUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
* @author 33249
* @description 针对表【device_data】的数据库操作Service实现
* @createDate 2025-08-24 16:27:16
*/
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData>
    implements DeviceDataService {

    @Autowired
    private DeviceService deviceService;

    /**
     * 批量插入设备数据
     * @param iotMsgNotifyData 消息接收对象
     */
    @Override
    @Transactional
    public void batchInsert(IotMsgNotifyData iotMsgNotifyData) {
        // 查询设备是否存在
        String iotId = iotMsgNotifyData.getHeader().getDeviceId();
        Device device = deviceService.lambdaQuery()
                .eq(Device::getIotId, iotId)
                .one();
        if (ObjectUtil.isEmpty(device)) {
            log.error(ErrorConstants.DEVICE_IS_NOT_EXIST.getMessage());
            return;
        }


        // 获取消息中的属性，循环遍历构造插入对象
        List<IotMsgService> services = iotMsgNotifyData.getBody().getServices();
        for (IotMsgService service : services) {
            // 获取属性值
            Map<String, Object> properties = service.getProperties();
            // 判断是否为空
            if (ObjectUtil.isEmpty(properties)) {
                continue;
            }

            // 获取上报时间并解析
            LocalDateTime eventTime = LocalDateTimeUtil.parse(service.getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
            //时区转换
            LocalDateTime alarmTime = eventTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();

            // 存储插入对象的集合
            List<DeviceData> deviceDataList = new ArrayList<>();

            // 遍历properties
            properties.forEach((k, v) -> {
                DeviceData deviceData = new DeviceData();
                BeanUtils.copyProperties(device, deviceData, "id");
                // 设置对应属性值
                deviceData.setFunctionId(k);
                deviceData.setDataValue(v.toString());
                deviceData.setAlarmTime(alarmTime);
                deviceData.setAccessLocation(device.getBindingLocation());

                deviceDataList.add(deviceData);
            });

            saveBatch(deviceDataList);
        }
    }
}
